package com.yyq.adms.usermanage.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.yyq.adms.sysmanage.pojo.DataDictionary;
import com.yyq.adms.sysmanage.pojo.SysModules;
import com.yyq.adms.usermanage.bpo.SysOnlineUsersBpo;
import com.yyq.adms.usermanage.bpo.SysUsersBpo;
import com.yyq.adms.usermanage.pojo.SysDepts;
import com.yyq.adms.usermanage.pojo.SysOnlineUsers;
import com.yyq.adms.usermanage.pojo.SysRPM;
import com.yyq.adms.usermanage.pojo.SysUsers;
import com.yyq.adms.usermanage.pojo.SysUsersRoles;
import com.yyq.sos.action.BaseAction;
import com.yyq.sos.constants.ActionType;
import com.yyq.sos.constants.Constants;
import com.yyq.sos.logs.LogerImpl;
import com.yyq.sos.logs.LoggerProxy;
import com.yyq.sos.permission.LoginUser;
import com.yyq.sos.permission.Permissions;
import com.yyq.sos.util.ObjectUtil;
import com.yyq.sos.util.page.PageFormData;


/**
 * 登录Action
 *
 * @author Administrator
 *
 */
@Controller("com.yyq.adms.usermanage.action.LoginAction")
@Scope("prototype")
public class LoginAction extends BaseAction
{
	private static final long serialVersionUID = -6879565713234286829L;
	//public static ThreadLocal userThread = new ThreadLocal();
	private SysUsers po = new SysUsers();
	
	private SysUsersBpo sysUsersBpo;

	private SysOnlineUsers onlineUsers;
	private SysOnlineUsersBpo sysOnlineUsersBpo;
	
	@Resource
	public void setSysUsersBpo(SysUsersBpo sysUsersBpo) {
		sysUsersBpo.setCls(po.getClass());
		this.sysUsersBpo = sysUsersBpo;
	}
	@Resource
	public void setSysOnlineUsersBpo(SysOnlineUsersBpo sysOnlineUsersBpo) {
		sysOnlineUsersBpo.setCls(SysOnlineUsers.class);
		this.sysOnlineUsersBpo = sysOnlineUsersBpo;
	}

	/**
	 * Action操作入口
	 */
	public String execute() throws Exception
	{
		super.setBpo(sysUsersBpo);
		super.setObj(po);
		return super.execute();
	}

	public String login()
	{
		String ip =null;
		if (this.getRequest().getHeader("x-forwarded-for") == null) {
			ip = this.getRequest().getRemoteAddr();
		}else {
			ip = this.getRequest().getHeader("x-forwarded-for");
		}
		LoginUser user = (LoginUser) this.getSession().getAttribute(
				Constants.LOGIN_USER);
		String[] flag = (String[])this.getFormValue("flag");
		String flagStr = flag==null?null:flag[0];

		
		
		if (user == null)
		{
			SysUsers vo = sysUsersBpo.login(po);
			//***************************************************************************************************
			String[] isIndexs = (String[])this.getFormValue("type");
			String isIndex = isIndexs==null?null:isIndexs[0];
			if(isIndex!=null&&"isIndex".equals(isIndex)){
				this.getSession().setAttribute("isIndex","isIndex");
				return null;
			}
			isIndex = (String)this.getSession().getAttribute("isIndex");
			if(this.getServletContext().getAttribute(ip)==null){
				
			}else if(this.getServletContext().getAttribute(ip)!=null&&isIndex==null){
				try {
					this.getServletContext().removeAttribute(ip);
					this.getResponse().sendRedirect(this.getContextPath()+"/login.action?cmd=logout");
				} catch (IOException e) {
					e.printStackTrace();
				} 
			}
			this.getSession().removeAttribute("isIndex");
			//***************************************************************************************************
			
			if (vo != null)
			{	
				if(!vo.getPassword().equals(po.getPassword())){
					this.setMsg("{processId:\"-1\",msg:\"登录失败，密码不正确\"}");
					return ActionType.ACTION_FAILSE;
				}
				
				this.getSession().setAttribute(Constants.PERMISSION,sysUsersBpo.getPermission(vo.getId()));
				
				user = new LoginUser();
				user.setFullName(vo.getFullName());
				user.setUserCname(vo.getUserCname());
				user.setUserName(vo.getUserName());
				user.setUserId(vo.getId());
				user.setDeptId(vo.getDeptId());
//				user.setIp(this.getRequest().getRemoteAddr());
				user.setIp(ip);
				po.setId(user.getUserId());
				//user.setPerms(new Permissions(user));
				List list = sysUsersBpo.search("from " + SysDepts.class.getName()
						+ " o where o.id=" + vo.getDeptId());
				user.setDeptCname(((SysDepts) list.get(0)).getDeptCname());
				user.setDeptLevel(((SysDepts) list.get(0)).getDeptLevel());
				user.setDeptType(((SysDepts) list.get(0)).getDeptType());
				SysDepts d = sysUsersBpo.getOrgDept((SysDepts) list.get(0));
				user.setOrgId(d.getId());
				user.setOrgname(d.getDeptCname());
				if(flagStr != null && flagStr.equals("back")){
					user.setUserType(Constants.USER_BACK);
				}else{
					
					user.setUserType(Constants.USER_PRE);
				}
				this.getSession().setAttribute(Constants.LOGIN_USER, user);
				
				LoginUser.userThread.set(user);
				logging("SUCCESS");
				onlineUsers=(SysOnlineUsers) sysOnlineUsersBpo.findByPk(vo.getId());//查询在线用户表，查看是否在线？
				if(onlineUsers != null){
					sysOnlineUsersBpo.delete(vo.getId());
				}

				//将信息保存到在线用户表
				onlineUsers=new SysOnlineUsers();
				onlineUsers.setUserId(user.getUserId());
				onlineUsers.setUsername(user.getUserName());
				onlineUsers.setOnlinests(1);
//				onlineUsers.setIp(this.getRequest().getRemoteAddr());
				onlineUsers.setIp(ip);
				onlineUsers.setMachinename(this.getRequest().getRemoteHost());
				sysOnlineUsersBpo.save(onlineUsers);
				
				if(flagStr != null && flagStr.equals("back")){
					
					return "backMain";
				}else{
					processSearchData();
					return SUCCESS;
				}
			}
			else
			{
				this.setMsg("{processId:\"-1\",msg:\"登录失败，用户名不存在\"}");
				return ActionType.ACTION_FAILSE;
			}
		}
		else
		{
			this.setMsg("{processId:\"-1\",msg:\"你已经登录，不用再登录了！\"}");
			if(flagStr != null && flagStr.equals("back")){
				return "backMain";
			}else{
				processSearchData();
				return SUCCESS;
			}
		}
	}

	private void processSearchData(){
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String sql = "";
		boolean gp = this.isGlobalPermissions("PatentApply");
		if(gp){
			sql = "from SysModules where moduleName<>'CommonLink' and sts='ACTV' and isMenu=1 and parentId=131 order by id asc";
		}else{
			sql =  "select distinct obj from "
				+ SysModules.class.getName()
				+ " obj,"
				+ SysUsersRoles.class.getName()
				+ " objUR,"
				+ SysRPM.class.getName()
				+ " objRPM "
				+ " where  obj.moduleName<>'CommonLink' and obj.parentId=131 and objUR.userId="
				+ user.getUserId()
				+ " and objUR.roleId=objRPM.roleId and objRPM.moduleId=obj.id and obj.isMenu=1 order by obj.id asc";
		}
		List list = sysUsersBpo.search(sql);
		List tempList = new ArrayList();
		for(int i=0;list!=null&&i<list.size();i++){
			SysModules obj = (SysModules)list.get(i);
			SysModules objTemp = new SysModules();
			objTemp.setId(obj.getId());
			objTemp.setModuleUrl(obj.getModuleUrl());
			objTemp.setModuleName(obj.getModuleName());
			objTemp.setModuleCname(obj.getModuleCname().replaceAll("\\s", ""));
			tempList.add(objTemp);
			//obj.setModuleCname(obj.getModuleCname().replaceAll("\\s", ""));
		}
		
		this.setFormValue("childTypeSel",tempList);
		if(gp){
			sql = "from SysModules where moduleName<>'CommonLink' and sts='ACTV' and isMenu=1 and parentId=132 order by id asc";
		}else{
			sql =  "select distinct obj from "
				+ SysModules.class.getName()
				+ " obj,"
				+ SysUsersRoles.class.getName()
				+ " objUR,"
				+ SysRPM.class.getName()
				+ " objRPM "
				+ " where  obj.moduleName<>'CommonLink' and obj.parentId=132 and objUR.userId="
				+ user.getUserId()
				+ " and objUR.roleId=objRPM.roleId and objRPM.moduleId=obj.id and obj.isMenu=1 order by obj.id asc";
		}
		list = sysUsersBpo.search(sql);
		tempList = new ArrayList();
		for(int i=0;list!=null&&i<list.size();i++){
			SysModules obj = (SysModules)list.get(i);
			SysModules objTemp = new SysModules();
			objTemp.setId(obj.getId());
			objTemp.setModuleUrl(obj.getModuleUrl());
			objTemp.setModuleName(obj.getModuleName());
			objTemp.setModuleCname(obj.getModuleCname().replaceAll("\\s", ""));
			tempList.add(objTemp);
			//obj.setModuleCname(obj.getModuleCname().replaceAll("\\s", ""));
		}
		this.setFormValue("tableNameSel", tempList);
		list = sysUsersBpo.search("from DataDictionary where parentId=161");
		if(gp){
			DataDictionary dd = new DataDictionary();
			dd.setParentId(po.getId());
			dd.setText("报送单位");
			dd.setValue("sentDep");
			list.add(dd);
		}
		this.setFormValue("searchPropertySel", list);
	}
	
	public String data()
	{
		
		return ActionType.ACTION_DATA_LIST;
	}
	

	public String logout()
	{
		String ip =null;
		if (this.getRequest().getHeader("x-forwarded-for") == null) {
			ip = this.getRequest().getRemoteAddr();
		}else {
			ip = this.getRequest().getHeader("x-forwarded-for");
		}
		if (this.getSession()!=null) {
			LoginUser user = (LoginUser) this.getSession().getAttribute(
					Constants.LOGIN_USER);
			if(user!=null)
				onlineUsers=(SysOnlineUsers) sysOnlineUsersBpo.findByPk(user.getUserId());
			if(onlineUsers!=null && user.getIp().equals(onlineUsers.getIp()))
				sysOnlineUsersBpo.delete(user.getUserId());
			//从上下文中取出该用户名是否超时的标示，如果ipFromContext存在，说明该用户名登录已超时，但可能是两个人同时用该用户名登录，所以要再次判断是哪个ip产生的超时
			String ipFromContext = this.getServletContext().getAttribute(ip)+"";
			if(ipFromContext!=null){
				this.getServletContext().removeAttribute(ip);
			}
			this.getSession().removeAttribute(Constants.LOGIN_USER);
			this.getSession().invalidate();
			LoginUser.userThread.set(user);
		}

		return ActionType.ACTION_LOGOUT;
	}

	private void logging(String ret)
	{
		String perms = (String) this.getRequest().getSession()
				.getServletContext().getAttribute("SYSLOGS");
		if (perms != null && !perms.toUpperCase().equals("TRUE"))
			return;
		new LoggerProxy(new LogerImpl()).setTableClass(null, "SS_SYS_USERS")
				.log(getCmd().toUpperCase(), ret);
	}

	public SysUsers getPo()
	{
		return po;
	}

	public void setPo(SysUsers po)
	{
		this.po = po;
	}
}
